<template>
  <div class="student-assignment-detail">
    <a-card :bordered="false">
      <a-page-header
        title="学生作业详情"
        :subtitle="assignmentData.id ? `ID: ${assignmentData.id}` : ''"
        @back="goBack"
      />

      <a-spin :spinning="loading">
        <a-descriptions
          title="基本信息"
          bordered
          :column="{ xxl: 3, xl: 3, lg: 3, md: 2, sm: 1, xs: 1 }"
        >
          <a-descriptions-item label="作业标题">{{ assignmentData.assignmentTitle || '无' }}</a-descriptions-item>
          <a-descriptions-item label="学生姓名">{{ assignmentData.studentName || '无' }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatDate(assignmentData.createTime) || '无' }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(assignmentData.status)">
              {{ getStatusText(assignmentData.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item v-if="assignmentData.gradeTime" label="批改时间">
            {{ formatDate(assignmentData.gradeTime) }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <div class="document-section">
          <h3>相关文档</h3>
          
          <div v-if="assignmentData.filePathForTeacher" class="document-item">
            <span class="document-label">教师作业文档：</span>
            <a-button type="primary" :href="assignmentData.filePathForTeacher" target="_blank">
              <template #icon><download-outlined /></template>
              下载作业文档
            </a-button>
          </div>
          
          <div v-if="assignmentData.filePath" class="document-item">
            <span class="document-label">学生提交文档：</span>
            <a-button type="primary" :href="assignmentData.filePath" target="_blank">
              <template #icon><download-outlined /></template>
              下载提交文档
            </a-button>
          </div>
          
          <a-alert 
            v-if="assignmentData.status === 'wait'" 
            type="warning" 
            message="待提交" 
            description="学生尚未提交作业" 
            show-icon
            style="margin-top: 16px;"
          />
          
          <a-alert 
            v-if="assignmentData.status === 'pending'" 
            type="info" 
            message="批改中" 
            description="作业正在由AI进行批改，请稍后查看结果" 
            show-icon
            style="margin-top: 16px;"
          />
          
          <a-alert 
            v-if="assignmentData.status === 'error'" 
            type="error" 
            message="批改出错" 
            description="批改过程中出现错误，请联系管理员" 
            show-icon
            style="margin-top: 16px;"
          />
        </div>
        
        <div v-if="assignmentData.aiThinkingProcess" class="thinking-process">
          <a-divider>AI批改思路</a-divider>
          <a-collapse>
            <a-collapse-panel key="1" header="查看AI批改思路">
              <div v-html="formatContent(assignmentData.aiThinkingProcess)"></div>
            </a-collapse-panel>
          </a-collapse>
        </div>

        <div v-if="assignmentData.status === 'completed' && assignmentData.gradingResult" class="grading-result">
          <a-divider>AI批改结果</a-divider>
          
          <a-card title="批改详情" class="grading-content-card">
            <div class="grading-content" v-html="formatGradingResult(assignmentData.gradingResult)"></div>
          </a-card>
        </div>

        <a-divider />

        <div class="operation-area">
          <a-space>
            <a-button @click="goBack">返回</a-button>
          </a-space>
        </div>
      </a-spin>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { DownloadOutlined } from '@ant-design/icons-vue'
import request from '@/utils/request'

// 定义类型接口
interface StudentAssignment {
  id?: number | string
  templateId?: number | string
  assignmentTitle?: string
  studentId?: number | string
  studentName?: string
  content?: string
  filePath?: string
  filePathForTeacher?: string
  aiThinkingProcess?: string
  status: string
  gradingResult?: string
  gradeTime?: string | Date
  createTime?: string | Date
}

const route = useRoute()
const router = useRouter()
const loading = ref<boolean>(false)
const assignmentData = reactive<StudentAssignment>({
  templateId: '',
  studentId: '',
  status: 'pending'
})

// 获取路由参数中的ID
const assignmentId = route.params.id as string

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "wait":
      return '待提交'
    case "pending":
      return '批改中'
    case 'completed':
      return '已完成'
    case 'error':
      return '错误'
    default:
      return '未知状态'
  }
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case "wait":
      return 'warning'
    case "pending":
      return 'processing'
    case 'completed':
      return 'success'
    case 'error':
      return 'error'
    default:
      return 'default'
  }
}

// 格式化日期
const formatDate = (date?: string | Date) => {
  if (!date) return '';
  const dateObj = typeof date === 'string' ? new Date(date) : date;
  return dateObj.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

// 格式化内容，清理换行符并重新组织
const formatContent = (content?: string) => {
  if (!content) return '';
  
  return content
    // 清理多余的换行符和空格
    .replace(/\n+/g, ' ')                    // 将所有连续换行符替换为空格
    .replace(/\s+/g, ' ')                    // 将多个连续空格合并为一个
    .trim()                                  // 去除首尾空白
    
    // 在句号后添加合理的换行
    .replace(/([。！？])\s*/g, '$1<br>')      // 句号后换行
    .replace(/([：:])\s*/g, '$1<br>')        // 冒号后换行
    
    // 清理多余的br标签
    .replace(/(<br\s*\/?>\s*){3,}/g, '<br><br>');
}

// 格式化批改结果 - 清理后端返回的格式问题
const formatGradingResult = (gradingResult: string) => {
  if (!gradingResult) return ''
  
  return gradingResult
    // 第一步：清理多余的换行符和空格
    .replace(/\n+/g, ' ')                    // 将所有连续换行符替换为空格
    .replace(/\s+/g, ' ')                    // 将多个连续空格合并为一个
    .trim()                                  // 去除首尾空白
    
    // 第二步：重新添加合理的段落结构
    .replace(/【([^】]+)】/g, '\n<strong>$1</strong>\n')  // 标题前后只添加单个换行
    
    // 第三步：处理特殊格式
    .replace(/\*\*([^*]+)\*\*/g, '<span style="font-weight: bold; color: #1890ff;">$1</span>')
    .replace(/(\d+\/\d+|\d+%)/g, '<span style="color: #52c41a; font-weight: bold; font-size: 16px;">$1</span>')
    .replace(/(第\s*\d+\s*题)/g, '<span style="color: #722ed1; font-weight: 500;">$1</span>')
    
    // 第四步：处理句号后的换行，重新组织段落
    .replace(/([。！？])\s*/g, '$1<br>')      // 句号后换行
    .replace(/([：:])\s*/g, '$1<br>')        // 冒号后换行
    
    // 第五步：最终换行处理
    .replace(/\n/g, '<br>')
    
    // 第六步：清理多余的br标签
    .replace(/(<br\s*\/?>\s*){3,}/g, '<br><br>')  // 多个br合并为两个
}

// 获取学生作业详情
const fetchAssignmentDetail = async () => {
  if (!assignmentId) {
    message.error('作业ID不存在')
    goBack()
    return
  }

  try {
    loading.value = true
    // 使用重试机制调用API
    const res = await request.retry({
      url: `/studentAssignments/get/${assignmentId}`,
      method: 'get'
    }, {
      count: 3, // 最多重试3次
      delay: 1000 // 每次重试间隔1秒
    })
    
    if (res.code === 200 && res.data) {
      // 调试：打印原始数据格式
      console.log('原始gradingResult:', res.data.gradingResult)
      if (res.data.gradingResult) {
        console.log('gradingResult字符编码:', [...res.data.gradingResult].map(char => char.charCodeAt(0)))
        console.log('包含换行符数量:', (res.data.gradingResult.match(/\n/g) || []).length)
      }
      
      // 将响应数据合并到reactive对象中
      Object.assign(assignmentData, res.data)
    } else {
      message.error(res.message || '获取学生作业详情失败')
      goBack()
    }
  } catch (error) {
    message.error('获取学生作业详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面加载时获取数据
onMounted(() => {
  fetchAssignmentDetail()
})
</script>

<style lang="less" scoped>
.student-assignment-detail {
  .document-section {
    margin: 24px 0;
    
    .document-item {
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      
      .document-label {
        margin-right: 16px;
        font-weight: 500;
        min-width: 120px;
      }
    }
  }
  
  .thinking-process {
    margin: 24px 0;
    
    :deep(.ant-collapse-content-box) {
      font-size: 14px;
      line-height: 1.8;
      color: #374151;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
      
      // 确保中文文本正常显示
      word-break: normal;
      word-wrap: break-word;
      white-space: normal;
      overflow-wrap: break-word;
      
      // 优化段落间距
      p {
        margin-bottom: 12px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  .grading-result {
    margin: 24px 0;
    
    .grading-content-card {
      margin-bottom: 24px;
      
      .grading-content {
        padding: 16px 20px;               // 减少上下内边距
        background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        font-size: 15px;
        line-height: 1.6;                 // 减少行间距
        color: #374151;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
        
        // 思考过程和批改结果的标题样式
        :deep(strong) {
          display: block;
          margin: 8px 0 12px 0;             // 减少上下边距
          padding: 10px 16px;               // 减少内边距
          background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
          color: white;
          border-radius: 6px;
          font-size: 15px;                  // 稍微减小字体
          font-weight: 600;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
          
          &:first-child {
            margin-top: 0;                  // 第一个标题无上边距
          }
        }
        
        // 优化文本间距和可读性 - 修复中文显示问题
        word-break: normal;
        word-wrap: normal;
        white-space: pre-wrap;
        overflow-wrap: normal;
        
        // 段落样式
        p {
          margin-bottom: 12px;
          word-break: normal;
          word-wrap: break-word;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
        
        // 确保中文文本正常显示
        br + br {
          display: block;
          margin: 8px 0;
          content: "";
        }
        
        // 滚动条样式（如果内容过长）
        max-height: 600px;
        overflow-y: auto;
        
        &::-webkit-scrollbar {
          width: 6px;
        }
        
        &::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 3px;
        }
        
        &::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 3px;
          
          &:hover {
            background: #a8a8a8;
          }
        }
      }
    }
  }
  
  .operation-area {
    margin-top: 24px;
    text-align: center;
  }
  
  :deep(.ant-collapse-header) {
    font-weight: 500;
  }
}
</style> 